package com.rockcent.api.helper;

import com.rockcent.common.BaseConfig;
import com.rockcent.common.utils.BaseCommonUtils;
import com.rockcent.mall.lib.helper.BaseSMSHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhangjh on 2016/11/8.
 */
@Component
public class SMSHelper extends BaseSMSHelper {

    private final Logger log = LoggerFactory.getLogger(SMSHelper.class);

    public static final String KEY = "MOBILE_CARD_";

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ExecutorService commonExecutorService;

    /**
     * 发送短信
     *
     * @param mobile   手机号码
     * @param timeLeft 有效时间(秒)
     * @return
     */
    public void sendCardCode(String mobile, String name, int timeLeft) {
        if (StringUtils.isEmpty(mobile)) {
            return;
        }
        String code = redisTemplate.boundValueOps(KEY + mobile).get();
        if (StringUtils.isNotEmpty(code)) {
            redisTemplate.delete(KEY + mobile);
        }
        String checkCode = BaseCommonUtils.getRandom6();
        redisTemplate.boundValueOps(KEY + mobile).set(checkCode);
        redisTemplate.expire(KEY + mobile, timeLeft, TimeUnit.SECONDS);
        //调用短信接口
        commonExecutorService.execute(() -> {
//            log.info("======================>sms msg send start");
//            send(mobile, "您的验证码是:" + checkCode);
            send(mobile, checkCode, name);

//            log.info("======================>sms msg send end");
        });
    }

    /**
     * 检验手机验证码是否有效
     *
     * @param mobile
     * @param code
     * @return
     */
    public boolean checkCodeEffective(String mobile, String code) {
        if (StringUtils.isEmpty(mobile)) {
            return false;
        }
        String cardCode = redisTemplate.boundValueOps(KEY + mobile).get();
        return StringUtils.isNotEmpty(cardCode) && StringUtils.isNotEmpty(code) && cardCode.equals(code) ? true : false;
    }
}
